package plus.eadydo.gateway.predicate;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import javax.validation.constraints.NotEmpty;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

/**
 * 自定义GateWay断言
 * @author yuzhanfeng
 */
@Component
public class AuthRoutePredicateFactory extends AbstractRoutePredicateFactory<AuthRoutePredicateFactory.Config> {


    private static final String NAME_KEY = "name";


    public AuthRoutePredicateFactory() {
        super(AuthRoutePredicateFactory.Config.class);
    }

    /**
     * 定义参数的前后顺序
     * @return list
     */
    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList(NAME_KEY);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return (exchange->{
            List<String> tokenList = exchange.getRequest().getHeaders().get(config.getName());
            return tokenList != null && tokenList.isEmpty();
        });
    }




    @Validated
    public static class Config {
        @NotEmpty
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

    }
}
